package de.stalinski.db;

import de.stalinski.logging.FrbrLogger;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;

public class CustomersConnector {


    private FrbrLogger logger = FrbrLogger.instance();
    private static String sUsr = "root";
    private static String sPwd = "admin";
    private static String sDB = "frbrUsers";
    private static String sTable = "customers";
    private static Connection connection;
    private static String sHost = "localhost";
    private static String sConn = "jdbc:mysql://" + sHost + ":3306/" + sDB;



    public CustomersConnector() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException ex) {
            logger.log(logger.LOG_ERR, ex.toString());
        }
        try {
            connection = DriverManager.getConnection(sConn, sUsr, sPwd);
            System.out.println(connection != null);
        } catch (SQLException ex) {
            logger.log(logger.LOG_ERR, ex.toString());
        }
    }

    public String getPrices() {
    String out ="<table class=\"Prices\"><thead>";
        try {
            Statement st = null;
            ResultSet rs = null;
            st = connection.createStatement();
            rs = st.executeQuery("select * from " + sTable);
            // Get meta data:
            ResultSetMetaData rsmd = rs.getMetaData();

            int i;
            int n = rsmd.getColumnCount();
            for(int a = 1; a <= rsmd.getColumnCount(); a++) {
                out+="<th>"+rsmd.getColumnName(a)+"</th>";
            }

            out+="<tbody>";
            while (rs.next()) {
                out+="<tr>";
                for (i = 1; i <= n; i++) {
                   out+="<td>"+rs.getString(i)+"</td>";
                }
                out+="</tr>";
            }
        } catch (SQLException ex) {
            logger.log(logger.LOG_ERR, ex.toString());
        }
        return out+"</tbody></thead></table>";
    }
}
